﻿using Furion.DependencyInjection;
using Microsoft.Extensions.Caching.Memory;
using MyProject.Enum;
using MyProject.IService.OrganizationManage;
using MyProject.IService.SystemManage;
using MyProject.Util;
using MyProject.Util.Helper;
using MyProject.Util.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace MyProject.Cache
{
    /// <summary>
    /// 用户信息缓存
    /// </summary>
    public class OperatorCache : ITransient
    {
        private string _userCacheKeyFix = CacheKeys.UserCacheFix.ParseToString();

        private readonly IMemoryCache _memoryCache;
        private readonly IUserService _userService;

        public OperatorCache(IMemoryCache memoryCache, IUserService userService) {
            _memoryCache = memoryCache;
            _userService = userService;
        }

        public async Task AddCurrent(string token)
        {
            OperatorInfo user = await _userService.GetUserByToken(token);
            if (user != null)
            {
                _memoryCache.Set(_userCacheKeyFix + token, user, DateTime.Now.AddDays(7));
            }
        }

        public async Task<OperatorInfo> Current(string token = "")
        {
            OperatorInfo user = null;

            // 如果没传token，就拿请求中的token
            if(token.IsEmpty())
                token = GetToken();

            if (string.IsNullOrEmpty(token))
                return user;
            
            user = _memoryCache.Get<OperatorInfo>(_userCacheKeyFix + token);

            if (user == null)
                user = await _userService.GetUserByToken(token);

            return user;
        }

        public void UpdateOperatorInfo(OperatorInfo user)
        {
            _memoryCache.Set(GetToken(), user, DateTime.Now.AddDays(7));
        }

        /// <summary>
        /// 获取token
        /// </summary>
        /// <returns></returns>
        public string GetToken() {
            string token = NetHelper.HttpContext.User.FindFirstValue("ApiToken").ParseToString();
            return token;
        }
    }
}
